<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
      <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title></title>
	<!-- Bootstrap Styles-->
    <link href="assets/css/bootstrap.css" rel="stylesheet" />
     <!-- FontAwesome Styles-->
    <link href="assets/css/font-awesome.css" rel="stylesheet" />
     <!-- Morris Chart Styles-->

        <!-- Custom Styles-->
    <link href="assets/css/custom-styles.css" rel="stylesheet" />
     <!-- Google Fonts-->
   <link href='https://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css' />
     <!-- TABLE STYLES-->
    <link href="assets/js/dataTables/dataTables.bootstrap.css" rel="stylesheet" />
</head>
<body>
    <div id="wrapper">
        <nav class="navbar navbar-default top-navbar" role="navigation">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".sidebar-collapse">
                    <span class="sr-only">Toggle navigation</span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                <a class="navbar-brand" ><i class="fa fa-gear"></i> <strong>学生成绩管理系统</strong></a>
            </div>

            <ul class="nav navbar-top-links navbar-right">

                <!-- /.dropdown -->

                <!-- /.dropdown -->

                <!-- /.dropdown -->
                <li class="dropdown">
                    <a class="dropdown-toggle" data-toggle="dropdown" href="#" aria-expanded="false">
                        <i class="fa fa-user fa-fw"></i> <i class="fa fa-caret-down"></i>
                    </a>
                    <ul class="dropdown-menu dropdown-user">
                        <li><a onclick=logout() style="cursor:pointer"><i class="fa fa-sign-out fa-fw"></i> 退出登录</a>
                        </li>
                    </ul>
                    <!-- /.dropdown-user -->
                </li>
                <!-- /.dropdown -->
            </ul>
        </nav>
        <!--/. NAV TOP  -->
        <nav class="navbar-default navbar-side" role="navigation">
            <div class="sidebar-collapse">
                <ul class="nav" id="main-menu">

                    <li>
                        <a style="cursor:pointer" id = "a"><i class="fa fa-desktop"></i> 返回</a>
                    </li>


                </ul>

            </div>

        </nav>
        <!-- /. NAV SIDE  -->
        <div id="page-wrapper" >
            <div id="page-inner">
			 <div class="row">
                    <div class="col-md-12">
                        <h1 class="page-header">

                            	课程管理 <small id="course_statistic"></small>
                        </h1>
                    </div>
                </div>
                 <!-- /. ROW  -->

            <div class="row">
                <div class="col-md-12">
                    <!-- Advanced Tables -->
                    <div class="panel panel-default">
                         <div class="row" style="margin-bottom: 20px;">
                            <div class="col-md-4">
                                <input type="text" id="search_course_name" class="form-control" placeholder="请输入课程名称">
                            </div>
                            <div class="col-md-4">
                                <input type="text" id="search_name_abbr" class="form-control" placeholder="请输入姓名拼音缩写（如 zs）">
                            </div>
                            <div class="col-md-12" style="margin-top: 10px;">
                                <button class="btn btn-primary" onclick="initPage()">查询</button>
                            </div>
                        </div>
                        <div class="panel-body">
                            <!-- 新增统计信息卡片 -->
                            <div class="row" id="summaryCards" style="margin-bottom: 20px;">
                                <div class="col-md-4">
                                    <div class="card text-white bg-primary mb-3">
                                        <div class="card-header">平均成绩</div>
                                        <div class="card-body">
                                            <h4 class="card-title" id="avgScore">--</h4>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="card text-white bg-success mb-3">
                                        <div class="card-header">标准差</div>
                                        <div class="card-body">
                                            <h4 class="card-title" id="stdDev">--</h4>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="card text-white bg-info mb-3">
                                        <div class="card-header">及格率</div>
                                        <div class="card-body">
                                            <h4 class="card-title" id="passRate">--</h4>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="table-responsive" id="container"></div>
                            <div><canvas id="canvas" width=400 height=300></canvas></div>
                        </div>

                        <script type="text/javascript">
                            // 计算统计数据的函数
                            function calculateStatistics(scoreRanges) {
                                // 验证输入数据
                                if (!scoreRanges || typeof scoreRanges !== 'object') {
                                    return { avg: 0, stdDev: 0, passRate: 0 };
                                }

                                var allScores = [];
                                var passedCount = 0;
                                var totalCount = 0;

                                // 处理不同格式的分数段（如"90-100"、"<60"、">90"）
                                for (var range in scoreRanges) {
                                    var count = parseInt(scoreRanges[range]) || 0;
                                    if (count <= 0) continue;

                                    totalCount += count;

                                    let minScore, maxScore;
                                    if (range.includes("-")) {
                                        // 处理区间格式（如"80-89"）
                                        const [min, max] = range.split("-").map(Number);
                                        minScore = min;
                                        maxScore = max;
                                    } else if (range.startsWith("<")) {
                                        // 处理下限格式（如"<60"）
                                        minScore = 0;
                                        maxScore = parseInt(range.slice(1)) - 1;
                                    } else if (range.startsWith(">")) {
                                        // 处理上限格式（如">90"）
                                        minScore = parseInt(range.slice(1)) + 1;
                                        maxScore = 100;
                                    } else {
                                        // 处理单一分数（如"100"）
                                        minScore = maxScore = parseInt(range);
                                    }

                                    // 计算区间中间值并生成对应数量的分数
                                    const midScore = (minScore + maxScore) / 2;
                                    for (let i = 0; i < count; i++) {
                                        allScores.push(midScore);
                                    }

                                    // 统计及格人数（60分及以上为及格）
                                    if (minScore >= 60) {
                                        passedCount += count;
                                    }
                                }

                                // 计算平均值（处理空数据情况）
                                const avg = allScores.length > 0
                                    ? allScores.reduce((sum, score) => sum + score, 0) / allScores.length
                                    : 0;

                                // 计算标准差（处理空数据或单数据情况）
                                let stdDev = 0;
                                if (allScores.length > 1) {
                                    const squaredDiffs = allScores.map(score => Math.pow(score - avg, 2));
                                    const variance = squaredDiffs.reduce((sum, diff) => sum + diff, 0) / (allScores.length - 1);
                                    stdDev = Math.sqrt(variance);
                                }

                                // 计算及格率（处理零人数情况）
                                const passRate = totalCount > 0
                                    ? passedCount / totalCount
                                    : 0;

                                return { avg, stdDev, passRate };
                            }

                            // 渲染表格
                            function renderTable(data) {
                                const container = document.getElementById("container");
                                container.innerHTML = ''; // 清空容器

                                const table = document.createElement("table");
                                table.className = "table table-striped table-bordered table-hover";

                                const thead = document.createElement("thead");
                                const headerRow = document.createElement("tr");
                                const gradeHeader = document.createElement("td");
                                const numberHeader = document.createElement("td");
                                gradeHeader.innerHTML = "分数段";
                                numberHeader.innerHTML = "人数";
                                headerRow.appendChild(gradeHeader);
                                headerRow.appendChild(numberHeader);
                                thead.appendChild(headerRow);
                                table.appendChild(thead);

                                const tbody = document.createElement("tbody");
                                for (const key in data) {
                                    const row = document.createElement("tr");
                                    const gradeCell = document.createElement("td");
                                    const numberCell = document.createElement("td");
                                    gradeCell.innerHTML = key;
                                    numberCell.innerHTML = data[key];
                                    row.appendChild(gradeCell);
                                    row.appendChild(numberCell);
                                    tbody.appendChild(row);
                                }
                                table.appendChild(tbody);
                                container.appendChild(table);
                            }

                            // 渲染图表
                            function renderChart(data) {
                                if (!data || Object.keys(data).length === 0) {
                                    return; // 没有数据，不渲染图表
                                }

                                const keyArray = [];
                                const valArray = [];
                                for (const key in data) {
                                    keyArray.push(key);
                                    valArray.push(data[key]);
                                }

                                // 生成饼图数据
                                const pieData = keyArray.map((key, index) => ({
                                    name: key,
                                    value: valArray[index]
                                }));

                                // 确保颜色数组足够长
                                const colors = ["Green", "Red", "Blue", "Yellow", "Purple", "Orange", "Pink", "Brown", "Gray", "Teal"];
                                while (pieData.length > colors.length) {
                                    colors.push(colors[Math.floor(Math.random() * colors.length)]);
                                }

                                pieChart(pieData, colors);
                            }

                            // 初始化页面
                            function initPage() {
                                var course_id = localStorage.getItem("course_id");
                                if (!course_id) {
                                    alert("未选择课程");
                                    return;
                                }

                                var studentId = document.getElementById("search_student_id").value.trim();
                                var courseName = document.getElementById("search_course_name").value.trim();
                                var nameAbbr = document.getElementById("search_name_abbr").value.trim();

                                var url = "/teacher/course_statistic?course_id=" + course_id;
                                if (studentId) url += "&student_id=" + encodeURIComponent(studentId);
                                if (courseName) url += "&course_name=" + encodeURIComponent(courseName);
                                if (nameAbbr) url += "&name_abbr=" + encodeURIComponent(nameAbbr);

                                var ajaxObj = new XMLHttpRequest();
                                ajaxObj.open('get', url);
                                ajaxObj.send();

                                ajaxObj.onreadystatechange = function () {
                                    if (ajaxObj.readyState == 4) {
                                        if (ajaxObj.status == 200) {
                                            console.log('数据返回成功');
                                            console.log(ajaxObj.responseText);

                                            try {
                                                var obj = JSON.parse(ajaxObj.responseText);

                                                // 计算统计数据
                                                var stats = calculateStatistics(obj);

                                                // 显示统计信息
                                                document.getElementById("avgScore").textContent = stats.avg.toFixed(2);
                                                document.getElementById("stdDev").textContent = stats.stdDev.toFixed(2);
                                                document.getElementById("passRate").textContent = (stats.passRate * 100).toFixed(2) + "%";

                                                // 渲染表格和图表
                                                renderTable(obj);
                                                renderChart(obj);
                                            } catch (error) {
                                                console.error("解析数据失败:", error);
                                                alert("数据格式错误，请稍后重试");
                                            }
                                        } else if (ajaxObj.status == 404) {
                                            var obj = JSON.parse(ajaxObj.responseText);
                                            alert(obj.error || "未找到课程数据");
                                        } else {
                                            alert("请求失败: " + ajaxObj.status);
                                        }
                                    }
                                };
                            }

                            // 页面加载完成后初始化
                            document.addEventListener('DOMContentLoaded', initPage);
                        </script>

                            <div class="table-responsive" id="container">

                            </div>
                            <div>  <canvas id="canvas" width=400 height=300></canvas></div>

                        </div>
                    </div>
                    <!--End Advanced Tables -->
                </div>
            </div>
                <!-- /. ROW  -->

                <!-- /. ROW  -->

                <!-- /. ROW  -->

                <!-- /. ROW  -->

             <!-- /. PAGE INNER  -->
            </div>
         <!-- /. PAGE WRAPPER  -->
     <!-- /. WRAPPER  -->
    <!-- JS Scripts-->
    <!-- jQuery Js -->
    <script src="assets/js/jquery-1.10.2.js"></script>
      <!-- Bootstrap Js -->
    <script src="assets/js/bootstrap.min.js"></script>
    <!-- Metis Menu Js -->
    <script src="assets/js/jquery.metisMenu.js"></script>
     <!-- DATA TABLE SCRIPTS -->
    <script src="assets/js/dataTables/jquery.dataTables.js"></script>
    <script src="assets/js/dataTables/dataTables.bootstrap.js"></script>
        <script>
            $(document).ready(function () {
                // 确保表格插件正确初始化
                if ($('#dataTables-example').length) {
                    $('#dataTables-example').dataTable();
                }
            });
    </script>
         <!-- Custom Js -->
    <script src="assets/js/mocustom-scripts.js"></script>

        <script type="text/javascript">
            // 保持原有功能不变
            var course_statistic = document.getElementById("course_statistic");
            course_statistic.innerHTML = "这是课程《" + localStorage.getItem("course_name") + "》的学生统计信息";

            document.getElementById("a").onclick = function () {
                window.location.href = "Teacher_Courses.html";
            }

            function logout() {
                if (confirm("您确定退出吗？")) {
                    window.location.href = "Login.html";
                }
            }

            // 画图函数保持不变
            var canvas = document.getElementById("canvas");
            var ctx = canvas.getContext("2d");
            var cw = canvas.width;
            var ch = canvas.height;

            ctx.lineWidth = 2;
            ctx.font = '12px verdana';

            var PI2 = Math.PI * 2;
            var myColor = ["Green", "Red", "Blue", "Yellow", "Purple"];
            var cx = 150;
            var cy = 150;
            var radius = 100;

            function pieChart(data, colors) {
                var total = 0;
                for (var i = 0; i < data.length; i++) {
                    total += +data[i].value;
                }
                var sweeps = [];
                for (var i = 0; i < data.length; i++) {
                    sweeps.push(data[i].value / total * PI2);
                }

                var accumAngle = 0;
                for (var i = 0; i < sweeps.length; i++) {
                    if (data[i].value !== 0) {
                        drawWedge(accumAngle, accumAngle + sweeps[i], colors[i], data[i], total);
                        accumAngle += sweeps[i];
                    }
                }
            }

            function drawWedge(startAngle, endAngle, fill, label, total) {
                // 绘制饼图扇区
                ctx.beginPath();
                ctx.moveTo(cx, cy);
                ctx.arc(cx, cy, radius, startAngle, endAngle, false);
                ctx.closePath();
                ctx.fillStyle = fill;
                ctx.strokeStyle = 'white';
                ctx.fill();
                ctx.stroke();

                // 绘制标签
                var midAngle = startAngle + (endAngle - startAngle) / 2;
                var labelRadius = radius * 0.75;
                var x = cx + 1.7 * labelRadius * Math.cos(midAngle) - 10;
                var y = cy + 1.7 * labelRadius * Math.sin(midAngle);
                ctx.fillStyle = 'black';
                ctx.fillText(label.name, x, y);
                const per = Math.round((label.value / total) * 10000) / 100; // 保留两位小数
                ctx.fillText(per + '%', x, y + 20);
            }
        </script>
    </body>
</html>